package web.dropwizard.healthCheck;

import com.codahale.metrics.health.HealthCheck;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

import java.io.File;

/**
 * @author Gregory Boissinot
 */
public class JenkinsHealthCheck extends HealthCheck {

    private final Client client;

    private final String url;

    private final String rootTemplateDir;

    public JenkinsHealthCheck(Client client, String url, String rootTemplateDir) {
        this.client = client;
        this.url = url;
        this.rootTemplateDir = rootTemplateDir;
    }

    @Override
    protected Result check() throws Exception {
        Result urlHealthResult = checkURLConnection();
        if (urlHealthResult.isHealthy()) {
            return checkTemplateDirExistence();
        }
        return urlHealthResult;
    }

    private Result checkURLConnection() throws Exception {
        WebResource resource = client.resource(url);
        ClientResponse clientResponse = resource.head();
        int statusCode = clientResponse.getStatus();
        if (statusCode == ClientResponse.Status.OK.getStatusCode()) {
            return Result.healthy();
        }
        return Result.unhealthy(String.format("Ping '%s' --> %d.", url, statusCode));
    }

    private Result checkTemplateDirExistence() {
        if (new File(rootTemplateDir).exists()) {
            return Result.healthy();
        }
        return Result.unhealthy(String.format("Template Dir '%s' doesn't exist.", rootTemplateDir));
    }
}
